# -*- coding : utf_8 -*-
"""
=======================================
Time : 2025/3/19 10:04
Author : 田霄汉
Email : 522989570@qq.com
File : csv_util.py
Project : pytest_demo
=======================================
"""

import csv
import os
from contextlib import ExitStack
import yaml
from jsonpath import jsonpath
from config.setting import file_path
from utils.log_util import logs
from utils.yaml_util import YamlUtil


class CsvUtil:

    @staticmethod
    def csv_replace_yaml(yaml_name):
        """
        将csv中的解析数据替换掉yaml中的$csv{}字段
        :param yaml_name: 需要解析的yaml文件名，yaml文件需要方式在testdata_yaml/testcase目录下面
        :return: 返回解析后yaml格式的data，用来做数据驱动
        """
        # 声明一个接收结果的列表
        result_list = []
        # yaml_file = "testcase/"+yaml_name
        yaml_path = os.path.abspath(os.path.join(file_path['testcase'], yaml_name))
        # 根据yaml读取对应的csv文件路径
        csv_name = jsonpath(YamlUtil().read_yaml_nokey(yaml_path), '$..name-appid-secret-grant_type-assert_str')[0]
        csv_path = os.path.abspath(os.path.join(file_path['csv'], csv_name))

        # 循环读取csv文件数据的每一行得到csvinfo_list
        # 举例：csvinfo_list = [{"name": "txh", "age": 36},{"name": "yyy", "age": 35}]
        with open(file=csv_path, mode='r', encoding="utf-8-sig") as f:
            # ★读取csv文件的内容★，得到csv文件里面每行数据以字典格式放在列表中
            reader = csv.DictReader(f)
            csvinfo_list = []
            for row in reader:
                csvinfo_list.append(dict(row))

        # 获取yaml文件的每一行，返回列表形式
        try:
            with ExitStack() as stack:
                yml_file = stack.enter_context(open(yaml_path, '+r', encoding='utf-8'))
                data_list = yml_file.readlines()
                # 循环csv文件中的测试用例行数
                for i in range(0, len(csvinfo_list)):
                    # 再循环yaml文件里面每一行内容
                    for data_str in data_list:
                        if '$csv{' in data_str and '}' in data_str and '#' not in data_str:
                            # 如果yaml文件中其中一行内容有多个$csv{}就循环多次，就全部都替换掉
                            for j in range(1, data_str.count('$csv{')+1):
                                # 根据“$csv{”和“}”来定位序号，取到里面的解析关键字evn_name
                                start_index = data_str.index('$csv{')
                                end_index = data_str.index('}', start_index)
                                evn_value = data_str[start_index:end_index+1]
                                evn_name = evn_value[5:evn_value.index('}')]
                                # ★将evn_value--->csvinfo_list[i][evn_name]★
                                if evn_name in csvinfo_list[i].keys():
                                    new_value = csvinfo_list[i][evn_name]
                                    # if new_value:
                                    #     logs.info(f'成功解析csv文件字段{evn_name}，解析结果为{new_value}')
                                    # else:
                                    #     logs.error(f'解析csv文件字段{evn_name}结果为空，请检查csv文件')
                                    data_str = data_str.replace(evn_value, new_value)
                        result_list.append(data_str)
                result_str = "".join(result_list)
                # ★将字符格式的data直接转换成yaml格式的★
                result_yaml = yaml.safe_load(result_str)
            logs.info('解析csv文件成功')
            return result_yaml

        except Exception as e:
            logs.error("$csv{}解析失败，报错信息：%s" % e)
